﻿using Lacrima.Framework.Infrastructure;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lacrima.Framework.Persistence
{
    /// <summary>
    /// 仓储接口的实现类，该类为抽象类，泛型类，
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class Repository<T> : IRepository<T> where T : class, new()
    {
        public IDbManager dbManager { get; set; }

        public Repository(IDbManager manager)
        {
            this.dbManager = manager;
            this.dbManager.Open();
        }

        /// <summary>
        /// 默认查询所有数据的方法
        /// </summary>
        /// <returns>IEnumerable{`0}.</returns>
        public virtual IEnumerable<T> QueryAll()
        {
            DataTable table = null;
            string sql = string.Format("SELECT * FROM {0}", typeof(T).Name);
            this.dbManager.ExecuteQuery(sql,out table);
            return table.ToEntityList<T>();
        }

        /// <summary>
        /// 通用查询
        /// </summary>
        /// <param name="querySQL">The query SQL.</param>
        /// <returns>IEnumerable{`0}.</returns>
        public virtual IEnumerable<T> Query(string querySQL)
        {
            DataTable table = null;
            this.dbManager.ExecuteQuery(querySQL, out table);
            return table.ToEntityList<T>();
        }

        /// <summary>
        /// 执行NonQuery操作
        /// </summary>
        /// <param name="nonQuerySQL">The non query SQL.</param>
        /// <returns>System.Int32.</returns>
        public virtual int Execute(string nonQuerySQL)
        {
            return this.dbManager.ExecuteNonQuery(nonQuerySQL);
        }

        /// <summary>
        /// 执行标量查询操作
        /// </summary>
        /// <typeparam name="TResult">The type of the t result.</typeparam>
        /// <param name="scalarSQL">The scalar SQL.</param>
        /// <returns>``0.</returns>
        public virtual TResult QueryScalar<TResult>(string scalarSQL)
        {
            return default(TResult);
        }

        public virtual void ExecuteDelegate(Delegate method)
        {
        }

        /// <summary>
        /// 默认查询所有数据的方法
        /// </summary>
        /// <returns>IEnumerable{`0}.</returns>
        public virtual DataTable QueryDefault()
        {
            DataTable table = null;
            string sql = string.Format("SELECT * FROM {0}", typeof(T).Name);
            this.dbManager.ExecuteQuery(sql, out table);
            return table;
        }
    }
}
